// Package middleware provides recovery middleware that reports panics to Sentry.
package middleware

import (
	"net/http"
	"time"

	"github.com/getsentry/sentry-go"
)

// Recovery captures panics, reports to sentry if configured, and returns 500.
func Recovery(next http.Handler) http.Handler {
	return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		defer func() {
			if rec := recover(); rec != nil {
				// report
				sentry.CurrentHub().Recover(rec)
				sentry.Flush(2 * time.Second)
				http.Error(w, "internal error", http.StatusInternalServerError)
			}
		}()
		next.ServeHTTP(w, r)
	})
}
